package com.dwxt.parabolic.service;

import ch.qos.logback.core.boolex.EventEvaluator;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.Page;
import com.dwxt.common.base.StatusCode;
import com.dwxt.common.base.YesOrNo;
import com.dwxt.common.util.DateUtils;
import com.dwxt.common.util.IDUtils;
import com.dwxt.parabolic.base.EventCode;
import com.dwxt.parabolic.base.LevelType;
import com.dwxt.parabolic.base.RoleType;
import com.dwxt.parabolic.dao.AreaMapper;
import com.dwxt.parabolic.dao.EventMapper;
import com.dwxt.parabolic.entity.*;
import com.dwxt.parabolic.event.EventUpload;
import com.dwxt.parabolic.utils.FileUtil;
import com.dwxt.parabolic.utils.RequestUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.commons.util.IdUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class EventService {
    @Autowired
    private EventMapper eventMapper;

    @Autowired
    private AreaMapper areaMapper;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private CameraService cameraService;

    @Autowired
    private ApplicationContext applicationContext;

    @Value("${gate.file.uploadPath}")
    private String uploadPath;

    @Value("${gate.file.realPath}")
    private String realPath;

    @Value("${gate.file.server}")
    private String server;

    public BaseResult getEventList(Page page, Event event, String parentId) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        EventExample example = new EventExample();
        example.setOrderByClause("create_time desc");
        EventExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(page.getStartTime())) {
            criteria.andCreateTimeBetween(DateUtils.formatTime(page.getStartTime()),
                    DateUtils.formatTime(page.getEndTime()));
        }
        if (StringUtils.isNotBlank(parentId)) {
            Area area = areaMapper.selectByPrimaryKey(parentId);
            if (area.getLevelType() == LevelType.ONE.getLevel()) {
                criteria.andProvinceIdEqualTo(parentId);
            } else if (area.getLevelType() == LevelType.TWO.getLevel()) {
                criteria.andCityIdEqualTo(parentId);
            } else {
                criteria.andAreaIdEqualTo(parentId);
            }
        }
        if (StringUtils.isNotBlank(event.getCompanyId())) {
            criteria.andCompanyIdEqualTo(event.getCompanyId());
        }
        if (Optional.ofNullable(event).map(Event::getStatus).isPresent()) {
            criteria.andStatusEqualTo(event.getStatus());
        }
        if (StringUtils.isNotBlank(event.getEventCode())) {
            criteria.andEventCodeEqualTo(event.getEventCode());
        }
        //所属那个安装公司
        if (RoleType.INSTALL_COMPANY.getType().equals(RequestUtil.getCurrentUserType())) {
            criteria.andInstallCompanyIdEqualTo(RequestUtil.getCurrentCompanyId());
        }
        List<Event> eventList = eventMapper.selectByExample(example);
        PageInfo pageInfo = new PageInfo(eventList);
        return BaseResult.ok(pageInfo);
    }

    public BaseResult add(Event event) {

        //System.out.println(Thread.currentThread().getName());
        //Event select = eventMapper.selectByPrimaryKey(event.getId());
        //摄像头信息
        Camera camera = cameraService.selectByPrimaryKey(event.getCameraId());
        //超脑信息
        Device device = deviceService.selectByPrimaryKey(camera.getDeviceId());
        //公司（小区）信息
        Company company = companyService.selectByPrimaryKey(device.getCompanyId());

        event.setId(IDUtils.genItemId());
        event.setCameraName(camera.getName());
        event.setCameraSerial(camera.getSerial());
        event.setCompanyAddress(company.getAddress());
        event.setCompanyId(company.getId());
        event.setCompanyName(company.getName());
        event.setInstallCompanyId(company.getInstallCompanyId());
        event.setDeviceId(device.getId());
        event.setDeviceName(device.getName());
        event.setDeviceSerial(device.getSerial());
        /*event.setPicName(event.getPicName());
        event.setVideoName(event.getVideoName());
        event.setRealVideoUrl(event.getRealVideoUrl());*/
        //事件（稿件）类型
        String eventCode = event.getEventCode();
        if (EventCode.PARABOLIC.getCode().equals(eventCode)) {
            event.setEventName(EventCode.PARABOLIC.getName());
        } else if (EventCode.DEVICE_ERROR.getCode().equals(eventCode)) {
            event.setEventName(EventCode.DEVICE_ERROR.getName());
        } else if (EventCode.CAMERA_ERROR.getCode().equals(eventCode)) {
            event.setEventName(EventCode.CAMERA_ERROR.getName());
        }
        //是否处理
        event.setStatus(YesOrNo.NO);
        //单个摄像头1分钟内是否上传过3条数据
        if (eventMapper.countByid(event.getId())> 3){
            return BaseResult.ok("数据上传超出限制");
        }
        //发送通知短信
        applicationContext.publishEvent(new EventUpload(this, event));
        event.setMessageDate(new Date());
        eventMapper.insertSelective(event);
        return BaseResult.ok();
    }

    public BaseResult update(Event event) {
        eventMapper.updateByPrimaryKeySelective(event);
        return BaseResult.ok();
    }

    public int countByCompanyIdAndTime(String companyId, long date, Integer type, String currentCompanyId) {
        return eventMapper.countByCompanyIdAndTime(companyId, date, type, currentCompanyId);
    }

    public void insertEvent(Device device) {
        Company company = companyService.selectByPrimaryKey(device.getCompanyId());
        Event event = new Event();
        event.setId(IDUtils.genItemId());
        event.setStatus(YesOrNo.NO);
        event.setEventCode(EventCode.DEVICE_ERROR.getCode());
        event.setEventName(EventCode.DEVICE_ERROR.getName());
        event.setDeviceSerial(device.getSerial());
        event.setDeviceName(device.getName());
        event.setDeviceId(device.getId());
        event.setCompanyId(company.getId());
        event.setCompanyName(company.getName());
        event.setCompanyAddress(company.getAddress());
        applicationContext.publishEvent(new EventUpload(this, event));
        event.setMessageDate(new Date());
        eventMapper.insertSelective(event);
    }

    public List<Event> selectByInstallCompanyId(String installCompanyId) {
        EventExample eventExample = new EventExample();
        if (!"0".equals(installCompanyId)) {
            eventExample.createCriteria().andInstallCompanyIdEqualTo(installCompanyId);
        }
        return eventMapper.selectByExample(eventExample);
    }

    public BaseResult load(String id) throws IOException {
        Event event = eventMapper.selectByPrimaryKey(id);
        String pic = realPath + event.getPicName().substring(server.length());
        String video = realPath + event.getVideoName().substring(server.length());
        String realVideo = realPath + event.getRealVideoUrl().substring(server.length());
        List<String> filePaths = Arrays.asList(pic, video, realVideo);
        String zipPath = realPath + uploadPath + "/event/zip/" + event.getId() + ".zip";
        FileUtil.compress(filePaths, zipPath, false);
        return BaseResult.ok(server + uploadPath + "/event/zip/" + event.getId() + ".zip");
    }

    public BaseResult selectById(String id) {
        Event event = eventMapper.selectByPrimaryKey(id);
        if (event!=null){
            return BaseResult.ok(event);
        }else {
            return BaseResult.build(500,"未查询到抛物事件",null);
        }
    }

}
